﻿package com.crl.core.config.impl
{
	
	import com.crl.core.config.section.SectionManager;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;

	/**
	 * ...
	 * @author crl
	 */
	public class Configuration extends EventDispatcher implements IConfiguration
	{
		private var sectionManager:SectionManager;
		private var loader:URLLoader;
		
		private var _loaded:Boolean = false;
		private var config:XML;
		public function Configuration() 
		{
			sectionManager=new SectionManager();
		}
		
		public function load():void {
			_loaded = false;
			var request:URLRequest = new URLRequest("data/config.xml");
			getLoader().load(request);
		}
		
		private function getLoader():URLLoader {
			if(loader==null){
				loader = new URLLoader();
				loader.dataFormat = URLLoaderDataFormat.TEXT;
				loader.addEventListener(Event.COMPLETE, completeHandler);
				loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
				loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, errorHandler);
			}
			return loader;
		}
		
		private function completeHandler(event:Event):void {
			
			config= new XML(loader.data);
			var configSections:XML = config.descendants("configSections")[0];
			
			var extenalSections:Dictionary = new Dictionary();
			
			var name:String;
			var type:String;
			for each(var section:XML in configSections.children()) {
				
				name = section.@name;
				type = section.@type;
				
				extenalSections[name] = type;
			}
			
			sectionManager.extenalSections = extenalSections;
			
			_loaded = true;
			
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function errorHandler(event:Event):void {
			this.dispatchEvent(event);
		}
		
		public function get loaded():Boolean {
			return this._loaded;
		}
		public function getSection(key:String):Object {
			var sectionNode:XML = getSectionNodeByKey(key);
			return sectionManager.getSection(key,sectionNode);
		}
		
		
		protected function getSectionNodeByKey(key:String):XML {
			return config.descendants(key)[0];
		}
		
	}

}